//@原文链接：https://editor.csdn.net/md/?articleId=123950416

class MyLinkedList {
public:
    struct ListNode{
        int val;
        ListNode* next;
        ListNode(int v):val(v),next(nullptr){}
    };
    MyLinkedList() {
        size = 0;
        head = new ListNode(0);
    }
    //注意区分这里的cur的初始值和后面的其他函数的初始值
    int get(int index) {
        if(index<0 || index>size-1) return -1;
        ListNode* cur = head->next;
        while(index--){
            cur = cur->next;
        }
        return cur->val;
    }
    
    void addAtHead(int val) {
        ListNode* newH = new ListNode(val);
        newH->next = head->next;
        head->next = newH;
        size++;
    }
    
    void addAtTail(int val) {
        ListNode* cur = head;
        ListNode* newT = new ListNode(val);
        while(cur->next != nullptr){
            cur=cur->next;
        }
        cur->next = newT;
        size++;
    }
    
    void addAtIndex(int index, int val) {
        if(index<0){
            addAtHead(val);
            return;
        } 
        if(index == size) {
            addAtTail(val);
            return;
        }
        if(index>size-1) return;
        ListNode* target = new ListNode(val);
        ListNode* cur = head;
        while(index--){
            cur = cur->next;
        }
        target->next = cur->next;
        cur->next = target;
        size++;
    }
    
    void deleteAtIndex(int index) {
        if(index<0 || index>size-1) return;
        ListNode* cur = head;
        ListNode* de = new ListNode(0);
        while(index--){
            cur= cur->next;
        }
        de = cur->next;
        cur->next = de->next;
        //C++需要自己释放内存
        delete(de);
        size--;
    }
private:
    int size;
    ListNode* head;
};

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList* obj = new MyLinkedList();
 * int param_1 = obj->get(index);
 * obj->addAtHead(val);
 * obj->addAtTail(val);
 * obj->addAtIndex(index,val);
 * obj->deleteAtIndex(index);
 */
